package com.rv.admin.delay;

import cn.hutool.core.thread.NamedThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
//@Component
public class DelayTaskExecutor implements Runnable {


    /**
     * 运行状态
     */
    private final AtomicBoolean running = new AtomicBoolean(false);

    /**
     * 延时队列
     */
    private final DelayQueue<DelayTask<?>> delayQueue = new DelayQueue<>();


    /**
     * 线程池
     */
    protected ExecutorService executor;



    public DelayTaskExecutor() {
        this.running.set(true);
        this.executor = new ThreadPoolExecutor(1,  2, 30, TimeUnit.SECONDS, new SynchronousQueue<>(), new NamedThreadFactory("DelayTask" , false));
        this.executor.execute(this);
    }

    /**
     * 提交任务
     *
     * @param delayTask 延时任务
     */
    public void submit(DelayTask<?> delayTask) {
        this.delayQueue.offer(delayTask);
    }


    @Override
    public void run() {
        while (this.running.get()) {
            try {
                DelayTask<?> delayTask = delayQueue.poll();
                if (delayTask != null) {
                    delayTask.handle();
                }
                // 暂停100ms
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.error("执行延时队列异常", e);
            }
        }
    }
}
